package ch.quantasy.android.remoteZapper;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

public class RemoteZapperIncomingSMSBroadcastReceiver extends BroadcastReceiver {
	public static final String TAG = "ZAP";

	@Override
	public void onReceive(final Context context, final Intent intent) {
		if (intent == null) {
			return;
		}
		Log.d(RemoteZapperIncomingSMSBroadcastReceiver.TAG, "Intent received: "
				+ intent);
		if (intent.getAction()
				.equals("android.provider.Telephony.SMS_RECEIVED")) {
			Log.d(RemoteZapperIncomingSMSBroadcastReceiver.TAG, "SMS Received");
			final Bundle bundle = intent.getExtras();
			if (bundle == null) {
				return;
			}
			final Object[] pdus = (Object[]) bundle.get("pdus");
			for (final Object pdu : pdus) {
				{
					if (pdu == null) {
						continue;
					}
					final String msg = SmsMessage.createFromPdu((byte[]) pdu)
							.getMessageBody();
					if (msg == null) {
						continue;
					}
					Log.d(RemoteZapperIncomingSMSBroadcastReceiver.TAG,
							"Message is: " + msg);
					final Intent zapperIntent = RemoteZapperService
							.getZapperIntent(msg);
					if (zapperIntent != null) {
						Log.d(RemoteZapperIncomingSMSBroadcastReceiver.TAG,
								"Sending intent to service");
						context.startService(zapperIntent);
						Log.d(RemoteZapperIncomingSMSBroadcastReceiver.TAG,
								"Intent sent to service");
					}
				}
			}
		}

	}
}
